<?php







/**



 * @Author: kendy



 * @Date:   2020-03-05 11:12:16



 * @Last Modified by:   jiayanting



 * @Last Modified time: 2020-04-01 14:46:45



 */



namespace app\api\controller;



use think\Db;



use think\Request;



use app\api\model\Bargain as b;

use app\common\model\BargainOrderModel as bom;

class Bargain extends Nocommon



{ 

  public function _initialize()

    {
        $where['is_have'] = ['IN',[0,1]];
        $data = Db::name('bargain_start')->field('id,create_time,is_have,goods_id')

            ->where($where) 

            ->select();

        if(count($data)>0){

          foreach ($data as $k => $v) { 

            //判断正在砍价的是否过期
            if($v['is_have'] == 0){
               if(strtotime($v['create_time']) + 24 * 60 * 60 <time()){

                Db::name('bargain_start')

                ->where('id',$v['id'])

                ->update(["is_have"=>2]); 
              //商品需要库存加一
               Db::name('bargain_goods')
               ->where(['id'=>$v['goods_id']])
               ->setInc("goods_number",1);
               }
            }
            //判断已经砍完的商品但是在该商品在砍价完成后的48h之内没有付款变成已过期，库存减一
            if($v['is_have'] == 1){
              //判断有没有支付
              $bargainGoods = Db::name('bargain_order')->where(['start_id'=>$v['id']])->find();
              //没有支付或是没有下订单的
               if(empty($bargainGoods) || $bargainGoods['order_status'] == 0){
                  //create_time + 24h + 48h if < time(),则为已过期
                  if(strtotime($v['create_time']) + 24 * 60 * 60  + 48 * 60 * 60 <time()){ 
                    Db::name('bargain_start') 
                    ->where('id',$v['id']) 
                    ->update(["is_have"=>2]); 
                 } 

               } 
               //商品需要库存加一
              Db::name('bargain_goods')->where(['id'=>$v['goods_id']])->setInc("goods_number",1);

            }
            

          }

        }

     

    }

    public function productlist()



    { 



      if(Request::instance()->isPost())



        {  



            $post = input('param.');



            $page = $this->p();



            $bargain = new b(); 



            $uid = $post['uid'];



            if(empty($uid)){



                return $this->apiReturn('400','用户信息为空',0); 

            } 

            $field = "id,goods_image,goods_name,goods_money,bargain_money";



            //正在进行中的砍价 

            //查看is_have为1是，未支付的

            $rs = Db::name('bargain_start')

            ->where(['uid'=>$uid,'is_have'=>array('in',[0,1])])

            ->select();

            //查看砍完价是否下订单或是支付的

             $startIds = [];

            if(count($rs)>0){

               foreach ($rs as $key => $value) {

                 $startIds[] = $value['id'];

               }

            }

            //查看订单表里是有发起id已经支付的

            $paystartIds = [];

            $orders = Db::name('bargain_order')

            ->where(['start_id'=>array('in',$startIds),'order_status'=>1])

            ->select();

            if(count($orders)>0){

               foreach ($orders as $key => $value) {

                 $paystartIds[] = $value['start_id'];

               }

            }

           $bargainingStartId = array_diff($startIds, $paystartIds);  

            $where['is_display'] = 1;



            $where['is_del'] = 0;   

            //已经支付了的，和已经过期的都可以买，除去正在进行中的

            

            $whereIng['bs.id'] = array('in',$bargainingStartId); 



            $result['bargaining'] = $bargain->bargaining($whereIng);



            //砍价列表



            $result['productlist'] = $bargain->productlist($where,$bargainingStartId,$uid,$field,$page);  



            return $this->apiReturn('200','成功',$result);



        }



   }



        

    public function bargainInfo(){

        $bargain = new b();

        $start_id = input('param.start_id');

        if(empty($start_id))

             return $this->apiReturn('400','砍价商品信息为空',0);

        $uid = input('param.uid');

        if(empty($uid))

             return $this->apiReturn('400','用户信息为空',0);

        //查看当前的砍价发起id是否存在

        $isHaveBargain = Db::name('bargain_start')

        ->field('u.user_icon,bs.uid')

        ->alias("bs")

        ->where("id",$start_id)

        ->join("user u",'u.uid = bs.uid','inner')

        ->find();

        if(empty($isHaveBargain)){

          return $this->apiReturn('400','无此砍价信息',0);

        }

     

        $othersPar = [];

        //查看当前用户是否是发起砍价的用户（是否是第三视角)

        $othersPar['is_others'] = 1; //默认是

        $othersPar['user_icon'] = $isHaveBargain['user_icon'];

        if($uid == $isHaveBargain['uid']){

            $othersPar['is_others'] = 0; 

        } 

        //正在进行中的砍价  

        $where['bs.id'] = $start_id; 

        $bargaining = $bargain->bargainInfo($where); 

        //第三方视角--------是否帮砍这次砍价默认不需要弹框 

        $bargaining['help_bargain_tips'] = 0;

        $is_help_bargain = Db::name('bargain_list') 

        ->where(["start_id"=>$start_id,'help_id'=>$uid]) 

        ->find();

        if(empty($is_help_bargain)){

             $bargaining['help_bargain_tips'] = 1;

        }

        //砍价列表

        $result = $bargain->bargainUserList($start_id);

        



        $bargainInfo = array_merge($bargaining,$othersPar,$result);

        return $this->apiReturn('200','成功',$bargainInfo);

    }



    /**

     * [submitBargainOrder 砍价生成订单]

     * @Author   kendy

     * @DateTime 2020-03-09T11:41:47+0800

     * @return   [type]                   [description]

     */

    public function submitBargainOrder()

    {

        if (Request::instance()->isPost()) {

            $b = new bom();

            $result = $b->submitBargainOrder();

        }

    }

   

    /**

     * [jlourule 砍价规则]

     * @Author   kendy

     * @DateTime 2020-03-09T11:44:02+0800

     * @return   [type]                   [description]

     */

    public function bargainrule()

    { 

        //查询用户协议列表

        $data = Db::name('bargain_rule')->field("content")->find();

        if ($data) {

            $this->assign('content', $data);

        }

        return $this->fetch();

    }



    /**

     * [isRead 弹框信息已读]

     * @Author   kendy

     * @DateTime 2020-03-09T15:18:37+0800

     * @return   boolean                  [description]

     */

    public function isRead(){

      if (Request::instance()->isPost()) {

           $start_id = input('param.id');

           if(empty($start_id)) 

            return $this->apiReturn('400','砍价发起id为空',0); 

            $result = Db::name('bargain_list')

            ->where('start_id',$start_id)

            ->update(['is_read'=>1]);

           return $this->apiReturn('200','已查看',0);

        }

    } 

    /**

     * [haveBargainRecord 已砍成记录]

     * @Author   kendy

     * @DateTime 2020-03-09T15:55:16+0800

     * @return   [type]                   [description]

     */

    public function haveBargainRecord(){

        if (Request::instance()->isPost()) {

           $userId = input('param.uid');

           if(empty($userId)) 

            return $this->apiReturn('400','用户信息为空',0); 

            $result = Db::name('bargain_order')

            ->alias('bo')

            ->field('bo.order_price,bo.order_status,goods_name,dk_code,is_send,bs.bargain_time')

            ->join("bargain_start bs",'bs.id = bo.start_id','inner')

            ->join('bargain_goods bg','bg.id = bs.goods_id','left')

            ->where('bo.uid',$userId)

            ->order('bs.bargain_time desc')

            ->select();

           return $this->apiReturn('200','请求成功',$result);

        }

    }

    /**

     * [bargainstart 开启砍价]

     * @Author   kendy

     * @DateTime 2020-03-11T09:51:07+0800

     * @return   [type]                   [description]

     */

    public function bargainstart(){

      //开启砍价，发起砍价，进入砍价表，帮砍用户表

       if(Request::instance()->isPost()) {

           $userId = input('param.uid');

           $goodsId = input('param.goods_id');

           if(empty($userId)) 

            return $this->apiReturn('400','用户信息为空',0); 

           if(empty($goodsId)) 

            return $this->apiReturn('400','商品信息为空',0); 

              

            //判断是否有该商品

            $goodsInfo = Db::name("bargain_goods")

            ->field('id,goods_money,bargain_money as low_money,goods_number')

            ->where(['is_display'=>1,'is_del'=>0,'id'=>$goodsId])

            ->find(); 
            if(empty($goodsInfo)){ 
                return $this->apiReturn('400','无此商品信息',0);  
            }
            if($goodsInfo['goods_number'] <1){

                return $this->apiReturn('400','商品库存不足',0); 

            } 
            //判断是否当前用户正在进行中的商品

            $bargaing =  Db::name('bargain_start')

            ->where(['uid'=>$userId,'goods_id'=>$goodsId,'is_have'=>0])

            ->find();

            if(!empty($bargaing)){

                 return $this->apiReturn('400','请勿重复砍价',0);

            }

            //商品需要库存减一
            Db::name('bargain_goods')->where(['id'=>$goodsId])->setDec("goods_number",1);



            //计算商品总价 如果低价为0，则为免费的，

            if($goodsInfo['low_money'] == 0){

                $needBargainMoney = $goodsInfo['goods_money'];

            }else{

                $needBargainMoney = $goodsInfo['goods_money'] - $goodsInfo['low_money'];  

            }

            

            $fKnifeBargainPercent = rand(80,90); 

            $fKnifeBargainMoney = $needBargainMoney * $fKnifeBargainPercent/100;  

            //用户第一刀砍价

            $start['goods_id'] = $goodsId;

            $start['uid'] = $userId;

            $start['bargain_count'] = 1;

            $start['bargain_money'] = $fKnifeBargainMoney;

            $start['create_time'] = date('Y-m-d H:i:s');
            
 

            $startId = Db::name('bargain_start')

            ->insertGetId($start);

            

            $bargainList['start_id'] = $startId;

            $bargainList['help_id'] = $userId;

            $bargainList['bargain_money'] = $fKnifeBargainMoney;

            $bargainList['create_time'] = date('Y-m-d H:i:s');

            $bargainList['is_read'] = 0; 

            $bargainAdd = Db::name('bargain_list')->insert($bargainList); 



           return $this->apiReturn('200','请求成功',$startId);

        }

      

    }

    /**

     * [HelpUserbargain 好友帮砍]

     * @Author   kendy

     * @DateTime 2020-03-11T16:02:46+0800

     */

    public function HelpUserbargain(){

         if(Request::instance()->isPost()) { 

            //帮砍好友id

            $userId = input('post.uid');

            $startId = input('post.start_id');

            if(empty($userId)) { 

              return $this->apiReturn('400','用户信息为空',0); 

            }

            if(empty($startId)){ 

             return $this->apiReturn('400','用户发起砍价id为空',0);

            }   

            //判断是否已经砍过价

            $bargains = Db::name('bargain_list')

            ->where(['start_id'=>$startId,'help_id'=>$userId])

            ->find();  

            if(!empty($bargains)){

                return $this->apiReturn('400','请勿重复帮砍价',0);

            }

            //该商品是否已经结束了

            $bargainStart = Db::name('bargain_start')

            ->alias('bs')

            ->field("bs.is_have,bs.create_time,new_people,bg.goods_money,bs.bargain_money,bs.bargain_count,bg.bargain_money as low_money")

            ->join("bargain_goods bg",'bg.id = bs.goods_id','inner')

            ->where(['bs.id'=>$startId,'is_display'=>1,'is_del'=>0]) 

            ->find();

            if(in_array($bargainStart['is_have'], [1,2]) || empty($bargainStart)){

                 return $this->apiReturn('400','该砍价已经结束',0);

            }

            //该砍价结束时间

            $end_time = strtotime($bargainStart['create_time']) + 24 * 60* 60;



            //本次砍价的金额

            $this_bargain_money = 0; 



            //帮砍的新人总数

            $total_new_peole = $bargainStart['new_people']; 



            $userInfo = Db::name('user')->where('uid',$userId)->find(); 

            //查新注册的用户

            if(strtotime($userInfo['create_time']) < $end_time){

                //是否帮砍过价

                $is_help_bargain = Db::name('bargain_list')

                ->where('help_id',$userId)

                ->find();

                if(empty($is_help_bargain)){

                    $total_new_peole = $total_new_peole + 1;

                }

                

            }  





            if($bargainStart['bargain_money'] == 0){ 

                $need_bargain_money = $bargainStart['goods_money'];

            }else{//不是免费拿 

                $need_bargain_money = $bargainStart['goods_money'] - $bargainStart['low_money'];

            } 



            $total_bargain_money = $bargainStart['bargain_money'] + $this_bargain_money;

            if($total_bargain_money > $need_bargain_money){

                $this_bargain_money = $need_bargain_money - $bargainStart['bargain_money'];

               }

            //帮砍价

            Db::startTrans();

           try{

            //判断是否砍价成功

            if($total_bargain_money == $need_bargain_money){

                $bargainDone['is_have'] = 1;

                $bargainDone['bargain_time'] = date('Y-m-d H:i:s');

                $updateres = Db::name('bargain_start')

                ->where('id',$startId)

                ->update($bargainDone); 

            }  

                     //增加砍价发起表 砍价次数，砍价价格,新人数

                    $updateData = array();

                    $updateData['bargain_count'] = $bargainStart['bargain_count'] + 1;

                    $updateData['bargain_money'] = $bargainStart['bargain_money'] + $this_bargain_money;

                    $updateData['new_people'] = $total_new_peole;

                    $rs =  Db::name('bargain_start')

                    ->where('id',$startId)

                    ->update($updateData);   

                    $bargainList['start_id'] = $startId;

                    $bargainList['help_id'] = $userId;

                    $bargainList['bargain_money'] = $this_bargain_money;

                    $bargainList['create_time'] = date('Y-m-d H:i:s');

                    $bargainList['is_read'] = 0; 

                    $bargainAdd = Db::name('bargain_list')->insert($bargainList); 

                

            Db::commit();

            return $this->apiReturn('200','砍价成功',$this_bargain_money); 

        }catch(\Exception $e){

            Db::rollback();

              return $this->apiReturn('400',$e->getMessage(),0); 

        }



         } 

            }

            

     

    /**

     * Undocumented function

     * type:post

     * param:user_id:用户id;start_id:砍价任务id

     */
    public function bargain()
    {

        if(request()->isPost()){

            $minBargainPercent = 0.1;
            $maxBargainPercent = 0.2;
    
            $param = request()->param();
    
            //查询该用户是否已经砍价
            $check = Db::name('bargain_list')->where(['help_id'=>$param['user_id'],'start_id'=>$param['start_id']])->find();

            if(!empty($check)){

                return json_encode(['code'=>'401','msg'=>'您已帮助好友砍价']);

            }else{

                //查询被砍商品当前价格
                $bargainObj = Db::name('bargain_start')->where('id',$param['start_id'])->find();
                $bargainGoods = Db::name("bargain_goods")->where('id',$bargainObj['goods_id'])->find();

                //判断砍价是否完成，如已完成禁止重复砍价
                if($bargainObj['is_have'] == 1){
                    return json_encode(['code'=>'401','msg'=>'砍价已完成请勿重复砍价']);
                    die;
                }

                //判断砍价时间是否已超时s
                $createTime = strtotime($bargainObj['create_time']);
                if (time()-$createTime>=86400) {
                    return json_encode(['code'=>'401','msg'=>'该活动已超时']);
                    die;
                }

                //$needBargainMoney = ($bargainGoods['goods_money']*100-$bargainGoods['bargain_money']*100-$bargainObj['bargain_money']*100)/100;
                $goodsNeedBargainMoney = bcsub($bargainGoods['goods_money'],$bargainGoods['bargain_money'],2); //两数相减，商品本身需要砍价价格
                $needBargainMoney = bcsub($goodsNeedBargainMoney,$bargainObj['bargain_money'],2);//两数相减，剩余需要砍的价格

                //判断剩余价格时是否低于2毛，低于两毛每次砍一分，新人砍两分
                if ($needBargainMoney*1 <= 0.2) {
                    
                    $bargainMoney = 0.01;

                }else{

                    //获取砍价范围,剩余价格的10%到20%之间
                    $minBargainMoney = round($needBargainMoney * $minBargainPercent, 2);
                    $maxBargainMoney = round($needBargainMoney * $maxBargainPercent, 2);

                    //获取砍价范围内的随机砍价数
                    $bargainMoney = mt_rand($minBargainMoney * 100, $maxBargainMoney * 100) / 100;

                }
                
                //判断用户是否为新人,如果是新人的话砍价加倍----1，注册时间晚于砍价发起时间；2，砍价者未砍过价；
                $helper = Db::name('user')->where("uid",$param['user_id'])->find();
                if (empty($helper)) {
                    return json_encode(['code'=>'401','msg'=>'用户不存在']);
                    die;
                }

                //查询该帮助人是否砍过价
                $helperBargain = Db::name("bargain_list")->where("help_id",$param['user_id'])->find();

                $helperRegisterTime = strtotime($helper['create_time']); //砍价者注册时间
                $bargainCreateTime = strtotime($bargainObj['create_time']);  //砍价活动创建时间

                $isNewUser = 0;
                if ($helperRegisterTime*1 > $bargainCreateTime*1 && empty($helperBargain)) {
                    $bargainMoney = $bargainMoney * 2; //新人砍价加倍
                    $isNewUser = 1;
                }

                //判断砍后的价格是否达到目标值
                //$noBargainMoney = ($needBargainMoney*100-$bargainMoney*100)/100;
                $noBargainMoney = bcsub($needBargainMoney,$bargainMoney,2);//两数相减，剩余未砍价格
            
                if ($noBargainMoney*1 <= $bargainGoods['bargain_money']*1) { //判断剩余钱数是否等于或低于目标值
        
                    //判断拉新人数是否完成，如果已完成，直接砍成；如果未完成，砍价0元
                    $nowNewUser = $bargainObj['new_people']*1+$isNewUser; //当前已拉新人数
                    if($nowNewUser < $bargainGoods['join_count']){ //如果拉新人数低于目标人数，此次砍价为0元

                        $bargainMoney = 0;

                    }else{

                        //两数相减，如果被砍剩余价格已经低于目标价格，则直接将价格砍到0元
                        $bargainMoney = bcsub($goodsNeedBargainMoney,$bargainObj['bargain_money'],2);

                        $updateBargainObj['bargain_time'] = date("Y-m-d H:i:s");
                        $updateBargainObj['is_have'] = 1;

                    }
                }

                //添加一条砍价记录-bargain_list
                $bargainListData['start_id'] = $param['start_id'];
                $bargainListData['help_id'] = $param['user_id'];
                $bargainListData['bargain_money'] = $bargainMoney;
                $bargainListData['create_time'] = date("Y-m-d H:i:s");
                Db::name('bargain_list')->insert($bargainListData);

                //更新砍价项目表-bargain_start
                $updateBargainObj['bargain_count'] = $bargainObj['bargain_count']*1+1;
                $updateBargainObj['bargain_money'] = bcadd($bargainObj['bargain_money'],$bargainMoney,2);

                $updateBargainObj['new_people']    = $bargainObj['new_people']*1 + $isNewUser;
                Db::name('bargain_start')->where("id",$param['start_id'])->update($updateBargainObj);
            
                return json_encode([
                    'code'=>'200',
                    'msg'=>'砍价成功',
                    'bargain_money'=>$bargainMoney.''
                    ]);

            } 
        }  
    }

 }